<?php

namespace app\common\model;

use app\admin\model\Region;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

class UserRecyclerInfo extends Model
{

    // 表名
    protected $name = 'user_recycler_info';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updateTime';

    // 追加属性
    protected $append = [
    ];

    public function base($query)
    {
        $query->where(['audit_state' => 1, 'status' => 1]);
    }

    /**
     * 获取回收员信息
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetail($params = [])
    {
        $where  = isset($params['where']) ? $params['where'] : ['id' => -1];
        $row    = $this->where($where)->order('id DESC')->find();
        if (!$row) {
            $this->error = '回收员不存在';
            return false;
        }

        if ($row['audit_state'] !== 1) {
            $this->error = '回收员审核未通过';
            return false;
        }

        if ($row['status'] !== 1) {
            $this->error = '回收员状态被锁定';
            return false;
        }

        $this->data($row->toArray());
        return true;
    }

    /**
     * Name: 回收片区申请
     * Date: 2021/12/19 18:58
     */
    public function recyclerApplication($params = [])
    {
        if ($params) {
            $result = false;

            if (!empty($params['id'])) {
                $this->error = __('禁止编辑');
                return false;
            }

            if ($this->where(['user_id' => $params['user_id']])->count()) {
                $this->error = __('请勿重复提交');
                return false;
            }

            if (!(new Region())->where(['id' => $params['region_id'], 'status' => 1])->count()) {
                $this->error = __('片区未找到或已关闭');
                return false;
            }

            Db::startTrans();
            try {
                $validate   = "app\\common\\validate\\UserRecyclerInfo.add";
                $result     = $this->validateFailException(true)->validate($validate)->allowField(true)->save($params);

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            } catch (PDOException $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            } catch (\Exception $e) {
                Db::rollback();
                $this->error = $e->getMessage();
                return false;
            }

            if ($result !== false) {
                return true;
            } else {
                $this->error = __('No rows were inserted');
                return false;
            }
        }

        $this->error = __('Parameter %s can not be empty', '');
        return false;
    }

    /**
     * 附近回收员
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function recyclersNearby($params = [])
    {
        if (Cache::tag('geo')->get('geo:recycler') !== true) {
            self::addUserRecyclerInfoToRedis();
        }

        list($lat, $lng) = !empty($params['site']) && strpos($params['site'], ',') !== false ? explode(',', $params['site']) : [DEFAULT_LATITUDE, DEFAULT_LONGITUDE];

        // 读取范围内的ID
        $redis = Cache::store('redis')->handler();
        $georadiuslist = [];
        if (method_exists($redis, 'georadius')) {
            $georadiuslist = $redis->georadius('geo:recycler', $lng, $lat, 50, 'km', ['WITHDIST', 'COUNT' => 5, 'ASC']);
        }

        $list = self::where(['id' => ['IN', array_column($georadiuslist, 0)]])->select();
        $data = [];

        foreach ($list as $v)
        {
            $data[] = [
                'latitude'  => $v['lat'],
                'longitude' => $v['lng'],
                'iconPath'  => '/static/car.png',
                'title'     => mb_strtoupper(mb_substr($v['name'], 0, 1)) . '师傅',
                'width'     => 35,
                'height'    => 25
            ];
        }

        return $data;
    }

    public static function addUserRecyclerInfoToRedis()
    {
        $list   = self::all();
        $redis  = Cache::store('redis')->handler();

        foreach ($list as $v) {
            if (method_exists($redis, 'geoadd')) {
                $redis->geoadd('geo:recycler', $v['lng'], $v['lat'], $v['id']);
            }
        }
        Cache::tag('geo')->set('geo:recycler', true, 60 * 60 * 24 * 7);
    }
}
